package com.lsk.admin.shop;

import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.task.SendCardTask;
import com.lsk.util.*;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jfinal.plugin.activerecord.Db.*;

/**
 * Created by Administrator on 2018/7/16 0016.
 */
public class ShopServices {

    Cache cache= Redis.use();

    /**
     * 获取分类下的所有商品
     *
     * @return
     */
    public PageUtil commodityListService(String page, String limit, String type,String classId) {


        String sql = "SELECT * from commodity where state!=3   ";

        String countSql = "SELECT count(*) from commodity where state!=3 ";

        if (type != null && !"".equals(type)) {
            sql += " and type=" + type;
            countSql += " and type=" + type;
        }

        if (classId != null && !"".equals(classId)) {
            sql += " and classId='"+classId+"'";
            countSql += " and classId='"+classId+"'";
        }


        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        List<Record> list = pageUtil.getList();
        /*for (Record r : list) {

            String commodityId = r.getStr("id");

            if (Db.queryInt("select count(id) from commodity_api_number where commodityId =?", commodityId) == 3) {
                Record commodityApiType = Db.findFirst(" select apiType from commodity_api_number where number =(select min(number) from commodity_api_number where commodityId =?) and \n" +
                        "\tcommodityId =?", commodityId, commodityId);

                r.set("apiType", commodityApiType.getStr("apiType"));
            } else {
                r.set("apiType", 4);
            }
        }*/

        return pageUtil;
    }

    /**
     * 根据商品ID获取对应的面值列表,分页
     *
     * @param page
     * @param limit
     * @param commodityId
     * @return
     */
    public PageUtil commodityFaceValueListService(String page, String limit, String commodityId) {
        String sql = "SELECT * from commodity_facevalue where commodityId ='" + commodityId + "' ORDER BY number  ASC  ";
        String countSql = "SELECT count(id) from commodity_facevalue where commodityId = '" + commodityId + "'";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);

        return pageUtil;
    }

    /**
     * 获取热门回收列表
     */
    public PageUtil hotService(String page, String limit) {

        String sql = "SELECT *from commodity where hotNumber is not null and state!=3";

        String countSql = "SELECT count(*) from commodity where hotNumber is not null and state!=3  ";

        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);

        return pageUtil;

    }


    /**
     * @param
     * @return
     */
    public Record editCommodityService(String id) {
        String sql = "SELECT *from commodity where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 根据Id查询FaceValue
     *
     * @param id
     * @return record
     */
    public Record getFaceValueById(String id) {
        return Db.findById("commodity_facevalue", id);
    }

    /**
     * 根据ID查询
     */
    public Record pingtaiId(String id) {
        return Db.findById("sk_commodity", id);
    }

    /**
     * 增加或更新facevalue,根据id判断是更新或者增加
     *
     * @return
     */
    public ReturnData saveFaceValue(Map<String, String[]> map) {
        ReturnData rd = new ReturnData();
        String id = map.get("id")[0];
        String commodityId = map.get("commodityId")[0];
        String faceValue = map.get("faceValue")[0];
        String number = map.get("number")[0];
        String discount = map.get("commodityDiscount")[0];
        String saleCardDiscount = map.get("saleCardDiscount")[0];
        boolean result = false;
        if (id != null && !id.isEmpty()) {
            //更新
            result = Db.update("commodity_facevalue", "id", new Record()
                    .set("id", id).set("commodityId", commodityId).set("faceValue", faceValue).set("number", number)
                    .set("discount", discount).set("saleCardDiscount", saleCardDiscount)
            );
        }
        if (id == null || "".equals(id)) {
            //新增
            id = UuidUtil.get32UUID();
            result = save("commodity_facevalue", new Record().set("id", id)
                    .set("commodityId", commodityId).set("faceValue", faceValue)
                    .set("number", number).set("discount", discount).set("saleCardDiscount", saleCardDiscount));
        }

        //设置返回
        rd.setResult(result);
        if (result) {
            rd.setMsg("创建成功");
            rd.setCode("000000");
        } else {
            rd.setMsg("创建失败");
            rd.setCode("111111");
        }
        return rd;
    }

    /**
     * 修改添加平台
     */
    public ReturnData updaSave(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String productId = map.get("productId")[0];
        String productName = map.get("productName")[0];
        boolean result = false;
        if (id != null && !id.isEmpty()) {
            result = Db.update("sk_commodity", "id", new Record()
                    .set("id", id).set("productId", productId).set("productName", productName));
        }
        if (id == null || "".equals(id)) {
            result = save("sk_commodity", new Record()
                    .set("productId", productId).set("productName", productName));
        }
        returnData.setResult(result);
        if (result) {
            returnData.setMsg("创建成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("创建失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 根据类型id获取类型信息
     *
     * @param id
     * @return
     */
    public Record classTypeByIdService(String id,String cType) {
        String sql = "SELECT *from commodity_class where id='" + id + "' and cType="+cType;
        Record record = Db.findFirst(sql);
        if (null==record)record=new Record().set("cType",cType);
        return record;
    }

    /**
     * 编辑显示
     */
    public Record kaPingtai(String id) {
        String sql = "select * from sk_commodity where id=" + id + "";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 保存商品
     */
    public ReturnData saveCommodityService(Map<String, String[]> map) {
        String id = map.get("id")[0];
        String productName = map.get("name")[0].trim();
        String discount = map.get("discount")[0].trim();
        String money = map.get("money")[0].trim();
        String classId = map.get("classId")[0].trim();
        String state = map.get("state")[0].trim();
        String imgPath = map.get("imgPath")[0].trim();
        String type = map.get("type")[0].trim();
        String remark = map.get("remark")[0].trim();
        boolean hasCarNumber = map.containsKey("hasCardNumber");
        String cardNumberState = hasCarNumber ? "0" : "1";
        String cardNumberSize = map.get("cardNumberSize")[0];
        String cardPasswordSize = map.get("cardPasswordSize")[0];
        double doubleMoney = Double.valueOf(money);
        String className = Db.findFirst("select name from commodity_class where id='" + classId + "'").getStr("name");
        boolean result = false;

        ReturnData returnData = new ReturnData();
        Record record = new Record().set("money", doubleMoney);
        if (id == null || "".equals(id)) {//新增商品
            record.set("id", UuidUtil.get32UUID()).set("name", productName).set("discount", discount).set("hasCardNumber", cardNumberState).set("cardNumberSize", cardNumberSize).set("cardPasswordSize", cardPasswordSize)
                    .set("state", state).set("classId", classId).set("imgPath", imgPath).set("type", type).set("remark", remark).set("className", className);
            result = save("commodity", "id", record);
        } else {
            record.set("id", id).set("name", productName).set("discount", discount).set("hasCardNumber", cardNumberState)
                    .set("cardPasswordSize", cardPasswordSize).set("cardNumberSize", cardNumberSize)
                    .set("state", state).set("classId", classId).set("imgPath", imgPath).set("type", type).set("remark", remark).set("className", className);
            result = Db.update("commodity", "id", record);
        }
        if (result) {
            returnData.setMsg("保存成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("保存失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 保存热门商品
     */
    public ReturnData saveHotCommodityService(Map<String, String[]> map) {
        boolean result = false;
        String id = map.get("id")[0];
        String hotNumber = map.get("hotNumber")[0].trim();
        Record record = new Record();
        record.set("id", id).set("hotNumber", hotNumber);
        result = Db.update("commodity", "id", record);
        ReturnData returnData = new ReturnData(result);
        return returnData;
    }


    /**
     * 保存商品类型
     *
     * @param map
     * @return
     */
    public ReturnData saveClassTypeService(Map<String, String[]> map) {
        String cType=map.get("cType")[0];
        String id = map.get("id")[0];
        String name = map.get("name")[0].trim();
        String logo = map.get("logo")[0].trim();
        String number = map.get("number")[0].trim();
        String rebatesThan=map.get("rebatesThan")[0];

        String refuel=map.get("refuel")[0];


        boolean result = false;
        ReturnData returnData = new ReturnData();
        Record record = new Record().set("logo", logo).set("number", number).set("name", name)
                .set("cType",cType).set("rebatesThan",rebatesThan).set("refuel",refuel);
        if (id == null || "".equals(id)) {//新增商品
            record.set("createTime", new Date()).set("synchronization",UuidUtil.get32UUID());

            List<Record> insertList=new ArrayList<>();


            if (map.get("0")!=null){

                Record insertRecord=new Record().setColumns(record).remove("id");

                insertRecord.set("cType",0).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }
            if (map.get("1")!=null){
                Record insertRecord=new Record().setColumns(record).remove("id");
                insertRecord.set("cType",1).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }
            if (map.get("2")!=null){
                Record insertRecord=new Record().setColumns(record).remove("id");
                insertRecord.set("cType",2).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }
            if (map.get("3")!=null){
                Record insertRecord=new Record().setColumns(record).remove("id");
                insertRecord.set("cType",3).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }
            if (map.get("4")!=null){
                Record insertRecord=new Record().setColumns(record).remove("id");
                insertRecord.set("cType",4).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }
            if (map.get("5")!=null){
                Record insertRecord=new Record().setColumns(record).remove("id");
                insertRecord.set("cType",5).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }

            if (map.get("6")!=null){
                Record insertRecord=new Record().setColumns(record).remove("id");
                insertRecord.set("cType",6).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }
            if (map.get("7")!=null){
                Record insertRecord=new Record().setColumns(record).remove("id");
                insertRecord.set("cType",7).set("id", UuidUtil.get32UUID());

                insertList.add(insertRecord);
            }


            int insertArr[] = Db.batchSave("commodity_class", insertList, insertList.size());

            result=true;
        } else {
            record.set("id", id);
            result = Db.update("commodity_class", "id", record);

            Syslog.info("123");
        }
        if (result) {
            returnData.setMsg("保存成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("保存失败");
            returnData.setCode("111111");
        }
        return returnData;

    }

    /**
     * 保存平台
     */
    public ReturnData savePingtai(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String productId = map.get("productId")[0].trim();
        String productName = map.get("productName")[0].trim();
        boolean result = false;
        Record record = new Record().set("productId", productId).set("productName", productName);
        if (id == null || "".equals(id)) {
            record.set("id", UuidUtil.get32UUID());
            result = save("sk_commodity", "id", record);
        } else {
            record.set("id", id);
            result = Db.update("sk_commodity", "id", record);
        }
        if (result) {
            returnData.setMsg("保存成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("保存失败");
            returnData.setCode("111111");
        }

        return returnData;
    }

    /**
     * 获取所有的商品类型
     */
    public List<Record> getAllCommodityClassService(String page, String limit,String type) {

        String sql = "SELECT * from commodity_class where state=0 and cType="+type+"  ORDER BY number DESC ";

        List<Record> list = Db.find(sql);


        return list;

    }

    public PageUtil getCommodityClassList(String page, String limit,String cType) {
        String sql = "select * from commodity_class where state = 0";
        if (StringUtils.isNotBlank(cType)){
            sql+=" and cType='"+cType+"'";
        }
        sql+=" order by number asc";
        String countsql = "select count(*) from commodity_class where state=0";
        if (StringUtils.isNotBlank(cType)){
            countsql+=" and cType='"+cType+"'";
        }
        PageUtil pageUtil = new PageUtil(Integer.valueOf(page), Integer.valueOf(limit), sql, countsql);
        return pageUtil;
    }

    /**
     * 根据id删除卡类型
     *
     * @param id
     * @return
     */
    public ReturnData delClassType(String id) {

        ReturnData rd = new ReturnData();
        int num = Db.queryInt("select count(*) from commodity where classId=? and   state !=3 ", id);
        if (num == 0) {
            String sql = "delete from commodity_class where id ='" + id + "'";
            int flag = Db.delete(sql);
            if (flag == 1) {
                rd.setResult(true);
            } else {
                rd.setResult(false);
            }
        } else {
            rd.setResult(false);
            rd.setMsg("该卡类下，共有"+num+"卡种，无法删除");
            List<Record> commodityNameList = Db.find("select name from commodity where classId=?", id);
            rd.setData(commodityNameList);
        }
        return rd;

    }


    /**
     * 注册商户
     */
    public ReturnData registerMerchantService(Map<String, String[]> map) throws Exception {
        ReturnData returnData = new ReturnData();
        String name = map.get("name")[0];//姓名
        String tel = map.get("tel")[0];//电话
        String address = map.get("address")[0];//地址
        String grade = map.get("grade")[0];//产品等级

        String userId = UtilUUID.getUUID();
        String salt = UtilUUID.getOrderIdByUUId();
        String password = AES.AESEncode(StringUtil.getPinYinHeadChar(name) + tel.substring(tel.length() - 4));
        Date date = new Date();
        String userCode = StringUtil.getPinYinHeadChar(name) + tel;
        String sql = "SELECT *from sys_user where userCode='" + userCode + "'";
        Record oldUser = Db.findFirst(sql);
        if (oldUser != null) {//账户已经存在
            returnData.setCode("111111");
            returnData.setMsg("账户已经存在");
        } else {
            Record user = new Record().set("id", userId).set("userCode", userCode).set("salt", salt)
                    .set("locked", "0").set("type", "1").set("phone", tel).set("adminUserId", "1")
                    .set("password", password).set("userName", name);
            boolean userBoolean = save("sys_user", "id", user);//保存用户
            Record org = new Record().set("name", name + "的店铺").set("tel", tel).set("person", name)
                    .set("address", address).set("createTime", date).set("startTime", date)
                    .set("endTime", DateUtil.getAfterDayDate("365")).set("adminUserId", userId)
                    .set("grade", grade);
            boolean orgBoolean = save("yx_org", "id", org);//保存用户
            if (userBoolean && orgBoolean) {//同时保存成功
                Map result = new HashMap();
                result.put("user", tel);
                result.put("password", AES.AESDncode(password));
                returnData.setData(result);
                returnData.setCode("000000");
                returnData.setMsg("保存成功");
            } else {//抛出异常，事务回滚
                throw new Exception();
            }
        }
        return returnData;
    }

    /**
     * 查询店铺-商品信息
     */
    public Map shopProductListData(String id, int page, int limit) {
        String sql = "SELECT\n" +
                "\tp.id as prouctId , p.productName,\n" +
                "\tp.productUnit,\n" +
                "\tIFNULL(shp.price,0) as price,\n" +
                "  shp.id\n" +
                "FROM\n" +
                "\tproduct p\n" +
                "LEFT JOIN shop_product shp ON p.id = shp.productId and shp.shopId='" + id + "' order by shp.id, shp.price desc  ";
        Map map = new HashMap();
        PageUtil pageUtil = new PageUtil(page, limit, sql);
        List<Record> list = pageUtil.getList();
        int count = pageUtil.getTotalRows();
        for (int i = 0; i < list.size(); i++) {
            Record record = list.get(i);
            String shpId = record.getStr("id");
            if (shpId == null || shpId == "") {
                record.set("state", "未配置信息");
            } else {
                record.set("state", "已配置");
            }
        }

        map.put("code", 0);
        if (count > 0) {
            map.put("count", count);
            map.put("data", list);
        } else {
            map.put("count", 0);
            map.put("msg", "暂无数据");
        }
        return map;
    }


    /**
     * 设定店家--商品信息
     *
     * @param id
     * @param money
     * @param state
     * @return
     */
    public ReturnData saveShopProductSettingService(String id, String money, String state, String prouctId, String shopId) {
        ReturnData returnData = new ReturnData();
        boolean sa = false;
        Record shopProduct = new Record().set("shopId", shopId).set("productId", prouctId).set("price", money);
        /*判断操作*/
        if ("0".equals(state)) {//取消配置
            if (id == null || "null".equals(id) || "".equals(id)) {//本来就没有
                sa = true;
            } else {
                shopProduct.set("id", id);
                sa = delete("shop_product", "id", shopProduct);
            }

        } else {//添加配置
            if (id == null || "null".equals(id) || "".equals(id)) {//该店家未设置该商品信息
                sa = save("shop_product", "id", shopProduct);
            } else {
                shopProduct.set("id", id);
                sa = Db.update("shop_product", "id", shopProduct);
            }
        }
        returnData.setResult(sa);
        return returnData;
    }


    /**
     * 保存店家信息
     *
     * @param map
     * @return
     */
    public ReturnData saveShopInfoServie(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        boolean result = false;
        String id = map.get("id")[0].trim();
        String name = map.get("name")[0].trim();
        String address = map.get("address")[0].trim();
        String principal = map.get("principal")[0].trim();
        String principalTel = map.get("principalTel")[0].trim();
        Record record = new Record().set("name", name).set("address", address)
                .set("principal", principal).set("principalTel", principalTel);
        if ("".equals(id) || id == null || "null".equals(id)) {//id为空
            record.set("id", UtilUUID.getUUID());
            result = save("shop", "id", record);
        } else {
            record.set("id", id);
            result = Db.update("shop", "id", record);
        }
        returnData.setResult(result);
        return returnData;
    }


    /**
     * 店铺详情
     *
     * @param id 店铺id
     * @return
     */
    public Record getShopInfoService(String id) {
        String sql = "SELECT *from shop where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }


    /**
     * 商户列表数据
     */
    public Map shopListDataService(int page, int limit) {
        Map map = new HashMap();
        String sql = "SELECT *from shop";
        PageUtil pageUtil = new PageUtil(page, limit, sql);
        List<Record> list = pageUtil.getList();
        int count = pageUtil.getTotalRows();
        map.put("code", 0);
        if (count > 0) {
            map.put("count", count);
            map.put("data", list);
        } else {
            map.put("count", 0);
            map.put("msg", "暂无数据");
        }
        return map;
    }

    /**
     * 轮播图信息
     */
    public List<Record> getSlideshowListService(String type) {

        String sql = "SELECT *from slideshowimg where 1=1 ";

        if ("".equals(type) || type==null || "null".equals(type)){

        }else {

            sql+=" and type='"+type+"' ";
        }


        List<Record> list = Db.find(sql);

        return list;

    }


    /**
     * 获取轮播图信息
     *
     * @param id
     */
    public Record getSlideshowInfo(String id) {

        String sql = "SELECT *from slideshowimg where id='" + id + "'";

        Record record = Db.findFirst(sql);

        return record;
    }

    /**
     * 保存轮播图
     *
     * @param map
     * @return
     */
    public ReturnData saveSlideshowService(Map<String, String[]> map) {

        boolean sa = false;

        String id = map.get("id")[0];

        String path = map.get("path")[0];

        String number = map.get("number")[0];

        String type=map.get("type")[0];

        Record record = new Record().set("path", path).set("number", number).set("type",type);

        if ("".equals(id)) { //新增

            record.set("id", UtilUUID.getUUID());

            sa = save("slideshowimg", "id", record);

        } else {

            record.set("id", id);

            sa = Db.update("slideshowimg", "id", record);

        }

        return new ReturnData(sa);

    }

    /**
     * 公告内容
     */
    public PageUtil noticeListService(String page, String limit,String type) {

        String sql = "SELECT *from notice where 1=1";
        String countSql = "SELECT count(*)  from notice where 1=1 ";

        if (StringUtils.isNotBlank(type)){
            sql+=" and type="+type;
            countSql+=" and type="+type;
        }

        sql+=" ORDER BY createTime desc ";


        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);

        return pageUtil;
    }

    /**
     * 公告内容
     */
    public Record getNoticeInfo(String id,String type) {

        String sql = "SELECT *from notice where id='" + id + "' and type="+type;

        Record record = Db.findFirst(sql);
        if (null==record)record=new Record().set("type",type);
        return record;

    }

    /**
     * 保存公告
     */
    public ReturnData saveNoticeService(Map<String, String[]> map) {

        boolean sa = false;

        String id = map.get("id")[0];

        String title = map.get("title")[0];

        String content = map.get("content")[0].trim();

        String type=map.get("type")[0];

        Record record = new Record().set("title", title).set("content", content).set("type",type);

        if ("".equals(id)) {//新增

            record.set("id", UtilUUID.getUUID());
            sa = Db.save("notice", "id", record);

        } else {

            record.set("id", id);

            sa = Db.update("notice", "id", record);
        }

        return new ReturnData(sa);
    }

    /**
     * 会员显示
     */
    public PageUtil ShowService(String page, String limit) {

        String sql = "SELECT * FROM yx_member";

        String countSql = "SELECT count(*) FROM yx_member ";

        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);

        return pageUtil;
    }

    /**
     * 分页查询Statistics列表
     *
     * @param map
     * @return
     */
    public PageUtil getStatisticsList(Map<String, String[]> map) {

        String limit[] = map.get("limit");
        String page[] = map.get("page");
        String limitStr = "";
        String pageStr = "";

        String orderState=map.get("orderState")[0];

        String cardNumber=map.get("cardNumber")[0];


        String memberId=map.get("memberId")[0];

        String startDate=map.get("startDate1")[0];

        String endDate=map.get("endDate1")[0];

        String className=map.get("className")[0];

        String cardPassWord=map.get("cardPassWord")[0];


        String feedbackValue=map.get("feedbackValue")[0];

        String payState=map.get("payState")[0];

        if (limit == null && page == null) {
            limitStr = "10";
            pageStr = "1";
        } else {
            limitStr = limit[0];
            pageStr = page[0];
        }
        String countSql = "SELECT count(*) FROM card where 1=1 ";


        String sql =" SELECT card.*,(card.feedbackValue*card.discount) as discountMoney from card where 1=1 ";

        if (StringUtils.isNotBlank(orderState) && orderState != "-1" && !"-1".equals(orderState)) { //实际为cardState
            String cardState = orderState;
            if (cardState == "0" || "0".equals(cardState)) {     //处理中 0 1 2
                countSql += "and  (state='1' or state = '2' or state='" + cardState + "')";
                sql += "and  (state='1' or state = '2' or state='" + orderState + "')";

            } else if (cardState == "3" || "3".equals(cardState)) {  //交易失败 3 6
                countSql += " and  ( state='" + cardState + "')";
                sql += " and ( state ='" + cardState + "')";
            } else {    //已打款 5 和 交易成功 4
                countSql += " and  state='" + cardState + "'";
                sql += " and  state ='" + cardState + "'";
            }
        }

        if (cardNumber != null && cardNumber != "") {
            countSql += " and cardNumber='" + cardNumber + "'";
            sql += " and cardNumber='" + cardNumber + "'";
        }


        if (cardPassWord != null && cardPassWord != "") {
            countSql += " and cardPassWord='" + cardPassWord + "'";
            sql += " and cardPassWord='" + cardPassWord + "'";
        }


        if ("".equals(memberId)==false && memberId!=null){

            countSql += " and memberId='" + memberId + "'";
            sql += "  and memberId='" + memberId + "'";
        }
        if ("".equals(className)==false && className!=null){

            countSql += " and className like'%" + className + "%'";
            sql += "  and className like '%" + className + "%'";
        }

        if ("".equals(feedbackValue)==false && feedbackValue!=null){

            countSql += " and feedbackValue ="+feedbackValue;
            sql += "  and feedbackValue ="+feedbackValue;
        }

        if (StringUtils.isNotBlank(payState) && payState != "-1" && !"-1".equals(payState)) { //实际为cardState

            countSql += " and payState ='"+payState+"' ";
            sql += "  and payState ='"+payState+"' ";
        }

        if (StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)){
            countSql+=" and date_format(createTime,'%Y-%m-%d') between '"+startDate+"' and '"+endDate+"'";
            sql+=" and date_format(createTime,'%Y-%m-%d') between '"+startDate+"' and '"+endDate+"'";
        }

        sql += "  group by id order by createTime desc ";
        countSql += " ";
        PageUtil pageUtil = new PageUtil(Integer.valueOf(pageStr), Integer.valueOf(limitStr), sql, countSql);

        /**添加推送网站字段*/
        List<Record> dataList = pageUtil.getList();
        for (Record temp : dataList) {

            String cardSendId = temp.getStr("cardSendId");
            if (cardSendId == null) {
                temp.set("sendWebSite", "未推送");
                continue;
            }
            String sendWebSite = cardSendId.substring(0, 2);
//            switch (sendWebSite) {
//                case "XK":
//                    temp.set("sendWebSite", "闲卡网");
//                    break;
//                case "SK":
//                    temp.set("sendWebSite", "收卡网");
//                    break;
//                case "YJ":
//                    temp.set("sendWebSite", "易缴费");
//                    break;
//                case "SXK":
//                    temp.set("sendWebSite", "易缴费");
//                    break;
//            }

        }
        return pageUtil;
    }

    /**
     * 返回今日订单和所有订单的相关信息
     *
     * @return
     */
    public ReturnData getSum(String date) {
        ReturnData rd = new ReturnData();
        Date tomorrow = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(tomorrow);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        tomorrow = calendar.getTime(); //今天
        Date today = new Date();
        String tomorrowStr = new SimpleDateFormat("yyyy-MM-dd").format(tomorrow);
        String todayStr = date;
        String sql="select count(c.id) as todayNum,sum(c.discount*c.feedbackValue) as todayDiscount  from `order` o left join card c on o.id=c.orderId where date(c.createTime) between date('" + todayStr + "')  and date('" + tomorrowStr + "')";
        String thisDaySql = sql;
        Record todayData = Db.findFirst(thisDaySql);
        String thisDaySqlDispose=sql+" and c.state in('0','1','2') ";
        Record toDayDispose = Db.findFirst(thisDaySqlDispose);
        /*今日支付统计*/
        String paySql="SELECT\n" +
                "\tCOUNT(*) AS payCount,\n" +
                "\tIFNULL(SUM(money), 0) AS payMoney \n" +
                "FROM\n" +
                "\tapply_logs\n" +
                "WHERE\n" +
                "\t (returnCode = '000000'\n" +
                "OR returnCode = '0')\n" +
                "AND DATE_FORMAT(createTime, '%Y-%m-%d') = '"+DateUtil.getDay()+"'";
        Record payData=Db.findFirst(paySql);
        Map<String, Object> map = new HashMap();
        map.put("today", todayData);
        map.put("todayDispose",toDayDispose);
        map.put("pay",payData);
        rd.setCode("000000");
        rd.setMsg("请求成功");
        rd.setResult(true);
        rd.setData(map);
        return rd;
    }

    public Map statisticsDataInfoDataService(String type,String date){

        Map resultMap=new HashMap();
        //type

        List<Record> dataList=new ArrayList<>();


        List<Record> classList=getCommodityClassList("1","10","").getList();


        for (int i=0;i<classList.size();i++){

            Record temp=classList.get(i);

            Record record=new Record();

            record.set("className",temp.getStr("name"));

            String countSql="SELECT c.feedbackValue,c.state,c.id from card c left join card_send_logs cs on c.id=cs.cardId   where DATE_FORMAT(c.createTime,'%Y-%m-%d')='"
                    +date+"' and c.classId='"+temp.getStr("id")+"' and cs.id like '"+type+"%'  order by cs.createTime desc   ";


            List<Record> countList=Db.find(countSql);

            int allNumber=countList.size();//总数量

            double allSum=0.00;//总金额

            int succeedNumber=0;//成功数量

            double succeedSum=0.00;//成功金额

            int fallNumber=0;//失败数量

            double fallSum=0.00;//是吧金额

            Map map=new HashMap();

            for (int j=0;j<countList.size();j++){

                Record card=countList.get(j);

                //Syslog.info("获取到的卡为："+card.toJson());
                allSum+=card.getDouble("feedbackValue");

                int state=card.getInt("state");

                String id=card.getStr("id");

                Object o=map.get(id);

                if (o==null){

                    switch (state){//提交

                        case 0:
                            break;
                        case 1://处理中
                            break;
                        case 2://推送成功
                            break;
                        case 3://推送失败
                            break;
                        case 4://已售出
                            succeedNumber+=1;
                            succeedSum+=card.getDouble("feedbackValue");
                            break;
                        case 5://已打款
                            succeedNumber+=1;
                            succeedSum+=card.getDouble("feedbackValue");
                            break;
                        case 6://销卡失败
                            fallNumber+=1;
                            fallSum+=card.getDouble("feedbackValue");
                            break;
                    }
                    map.put(id,id);
                }


            }
            record.set("allNumber",allNumber+"").set("allSum",allSum+"").set("succeedNumber",succeedNumber+"")
                    .set("succeedSum",succeedSum+"").set("fallNumber",fallNumber+"").set("fallSum",fallSum+"");
            dataList.add(record);

        }

        resultMap.put("code",0);resultMap.put("msg","请求成功");resultMap.put("count","6");resultMap.put("data",dataList);


        return resultMap;
    }


    /**
     * 显示一级菜单
     */
    public ReturnData caidan() {
        ReturnData returnData = new ReturnData();
        String sql = "SELECT commodityTypeName from xy_commodity GROUP BY commodityTypeName";
        List<Record> list = Db.find(sql);
        returnData.setData(list);
        return returnData;
    }


    /**
     * 列表显示卡
     */
    public PageUtil showKa(String page, String limit, String commodityTypeId) {
        String sql = "SELECT * from xy_commodity ";
        String countSql = "SELECT COUNT(*) from xy_commodity  ";
        if (!"null".equals(commodityTypeId) && !"".equals(commodityTypeId) && commodityTypeId != null) {//一级权限列表
            sql += " where commodityTypeName ='" + commodityTypeId + "'";
            countSql += "where commodityTypeName='" + commodityTypeId + "'";
        }
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        List<Record> list = Db.find(sql);
        return pageUtil;
    }

    public Record getSuXiaoKa(Integer id) {
        String sql = "SELECT * from commodity_sxk where id = " + id;
        return Db.findFirst(sql);
    }

    /**
     * 速消卡列表
     */

    public PageUtil showSuXiaoKa(String page, String limit,String facevalueId) {
        String sql = "SELECT * from commodity_sxk ";
        String countSql = "SELECT count(*) from commodity_sxk ";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);

        return pageUtil;
    }



    /**
     * 查看一级所有菜单
     */
    public ReturnData topMenu() {
        ReturnData returnData = new ReturnData();
        String sql = "select * from xy_commodity ";
        List<Record> list = Db.find(sql);
        returnData.setData(list);
        return returnData;
    }


    /**
     * 展示收卡啦列表
     *
     * @param limit
     * @param page
     * @return
     */
    public PageUtil showSKList(String limit, String page,String key) {

        String countSql = "select count(id) from sk_commodity where 1=1 ";
        String sql = "select * from sk_commodity where 1=1 ";

        if ("".equals(key)==false && key!=null && "null".equals(key)==false){

            countSql+=" and productName like '%"+key+"%' ";

            sql+=" and productName like '%"+key+"%' ";
        }

        sql+=" order by productId ";
        PageUtil pageUtil = new PageUtil(Integer.valueOf(page), Integer.valueOf(limit), sql, countSql);
        return pageUtil;
    }


    /**
     * 取消关联
     *
     * @return
     */

    @Before(Tx.class)
    //抛出异常事务回滚,写错了,service不回滚
    ReturnData cancelConn(String xkId, boolean isConn, String feedbackId) {
        String sql = "";

        if (isConn) {
            String commodityType = Db.queryStr("select type from commodity where id =(select commodityId from commodity_facevalue where  id=?)", feedbackId);

            sql = "update commodity_facevalue set xkCommodityId = null where xkCommodityId =? and commodityId in(select id from commodity where type=?)";         //删除原本关联该条闲卡的礼品卡记录

            Db.update(sql, xkId, commodityType);
            sql = "update commodity_facevalue set xkCommodityId=" + xkId + " where id='" + feedbackId + "'";

        } else {
            sql = "update commodity_facevalue set xkCommodityId= null where id = '" + feedbackId + "'";
        }
        int flag = update(sql);
        ReturnData rd = new ReturnData();
        if (flag > 0) {
            rd.setResult(true);
        } else {
            rd.setResult(false);
        }
        return rd;
    }

    /**
     * 配置完商品信息后更新订单card状态重新推送
     *
     * @param commodityId
     */
    public ReturnData reSubmit(String commodityId) {

        ReturnData rd = new ReturnData();



        int row = Db.update("update card set state = 0,msg=? where commodityId = ? and state=1", "重新推送", commodityId);



        if (row >= 1) { //如果有多于一条订单被修改为未处理状态



            new SendCardTask().run();
            rd.setResult(true);
            rd.setMsg("已重新推送");
        } else {
            rd.setResult(false);
            rd.setMsg("没有订单重新推送");
        }
        return rd;
    }

    /**
     * 显示其他平台商品
     */
    public PageUtil showPingtai(String page, String limit) {
        String sql = "SELECT * from sk_commodity";
        String countSql = "SELECT COUNT(*) from sk_commodity";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    /**
     * 接口顺序列表
     */
    public List<Record> apiNumberService(String faceValueId) {

        List<Record> list = new ArrayList<>();

        Record xk = new Record().set("faceValueId", faceValueId).set("apiType", 1).set("number", 1).set("name", "闲卡网");

        Record yjf = new Record().set("faceValueId", faceValueId).set("apiType", 0).set("number", 2).set("name", "易缴费");

        Record skl = new Record().set("faceValueId", faceValueId).set("apiType", 2).set("number", 3).set("name", "收卡啦");

        Record sxk = new Record().set("faceValueId", faceValueId).set("apiType", 3).set("number", 4).set("name", "速销卡");

        Record mf = new Record().set("faceValueId", faceValueId).set("apiType", 4).set("number", 5).set("name", "蜜蜂");


        list.add(xk);

        list.add(yjf);

        list.add(skl);

        list.add(sxk);

        list.add(mf);

        String sql = "SELECT *from commodity_api_number where faceValueId='" + faceValueId + "'";


        List<Record> dbList = Db.find(sql);


        for (int i = 0; i < dbList.size(); i++) {

            Record temp = dbList.get(i);

            int type = temp.getInt("apiType");

            for (int j = 0; j < list.size(); j++) {

                Record listTemp = list.get(j);

                int listTempType = listTemp.getInt("apiType");

                if (type == listTempType) {

                    listTemp.set("number", temp.getInt("number"));
                }
                list.set(j, listTemp);

            }

        }


        return list;

    }

    /**
     * 保存接口序号
     */
    public ReturnData saveApiNumberService(Map<String, String[]> map) {

        List<Record> list = new ArrayList<>();

        String faceValueId = map.get("faceValueId")[0];

        /*先进行删除*/

        String delSql = "DELETE from commodity_api_number where faceValueId='" + faceValueId + "'";

        Db.delete(delSql);

        for (String key : map.keySet()) {

            if ("faceValueId".equals(key) == false) {
                Record record = new Record().set("faceValueId", faceValueId)
                        .set("apiType", key).set("number", map.get(key)[0]);
                list.add(record);
            }
        }

        int[] inArr = Db.batchSave("commodity_api_number", list, list.size());

        boolean sa = BatchCheck.check(inArr);

        return new ReturnData(sa);

    }

    /**
     * 获取支付宝配置信息列表
     *
     * @return
     */
    ReturnData getElementsList() {
        ReturnData rd = new ReturnData();
        List<Record> list = Db.find("select * from sys_config where input= 0");
        rd.setData(list);
        rd.setMsg("success");
        rd.setResult(true);
        return rd;
    }

    /**
     * 删除商品
     */
    public ReturnData delCommodityService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String sql = "update commodity set state=3  WHERE id='" + id + "'";
        int del = Db.update(sql);
        if (del == 1) {
            returnData.setResult(true);
        } else {
            returnData.setResult(false);
        }
        return returnData;
    }


    public ReturnData deleLunbotu(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];

        String sql = "DELETE from slideshowimg where id='" + id + "'";
        int del = delete(sql);
        if (del == 1) {
            returnData.setCode("000000");
            returnData.setResult(true);

        } else {
            returnData.setCode("111111");
            returnData.setResult(false);
        }
        return returnData;
    }

    /**
     * 删除其他平台商品
     */
    public ReturnData delePingtai(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String sql = "DELETE FROM sk_commodity where id=" + id + "";
        int del = delete(sql);
        if (del == 1) {
            returnData.setCode("000000");
            returnData.setResult(true);
        } else {
            returnData.setCode("111111");
            returnData.setResult(false);
        }
        return returnData;
    }

    /**
     * 修改值
     *
     * @param element
     * @param value
     * @return
     */

    ReturnData updatePayInfo(String element, String value) {
        Record record = new Record().set("value", value);
        String updateSql = "update sys_config set value='" + value + "' where element='" + element + "'";
        int flag = Db.update(updateSql);
        ReturnData rd = new ReturnData((flag == 1 ? true : false));
        return rd;
    }

    /**
     * 查询sys_config列表中的各接口状态
     */
    ReturnData NetList() {
        ReturnData rd = new ReturnData();
        List<Record> list = Db.find("select * from sys_config where element in('sklstate','xkstate','yjfstate','suxiaoka', 'mifeng')");
        rd.setData(list);
        return rd;
    }

    /**
     * 设置接口开关
     *
     * @return
     */
    ReturnData setInterfaceState(String element, String value) {
        ReturnData rd = new ReturnData();
        int flag = Db.update("update sys_config set value ='" + value + "' where element = '" + element + "'");
        rd.setResult(flag == 1 ? true : false);
        return rd;
    }


    /**
     * @param
     * @return
     */

    public ReturnData updasave(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String productId = map.get("productId")[0];
        String productName = map.get("productName")[0];
        boolean result = false;
        if (id != null && !id.isEmpty()) {
            //更新
            result = Db.update("sk_commodity", "id", new Record()
                    .set("id", id).set("productId", productId).set("productName", productName));


        }
        if (id == null || "".equals(id)) {
            //新增
            id = UuidUtil.get32UUID();
            result = save("sk_commodity", new Record().set("id", id)
                    .set("productId", productId).set("productName", productName));
        }

        //设置返回
        returnData.setResult(result);
        if (result) {
            returnData.setMsg("创建成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("创建失败");
            returnData.setCode("111111");
        }
        return returnData;
    }


    public Record updasave(String id) {
        return Db.findById("commodity_facevalue", id);
    }


    public PageUtil memberMan(String page, String limit, String type, String name) {
        String sql = "SELECT * from yx_member where 1=1 ";
        String countSql = "SELECT count(*) from yx_member where 1=1";
        if (type != null && !"".equals(type)) {



            sql += " and type=" + type;
            countSql += " and type=" + type;
        }
        if (name != null && !"".equals(name)) {
            sql += "  and (id ='"+name.trim()+"' or alipayId='"+name.trim()+"' or  alipayAccount='"+name.trim()+"')  ";
            countSql += " and (id ='"+name.trim()+"' or alipayId='"+name.trim()+"' or  alipayAccount='"+name.trim()+"')  ";
        }
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    /**
     * 根据cardId获取待支付用户信息
     *
     * @return
     */
    public Record getAllPayInfo(String id) {

        String querySql = "select c.id as cardId , ym.realName, ym.alipayAccount ,ym.alipayId,(c.feedbackValue * c.discount) as money " +
                " from `order` o left join card c on c.orderId = o.id " +
                "left join yx_member ym on o.memberId = ym.id where c.id=? ";
        Record record = Db.findFirst(querySql, id);
        return record;
    }

    /**
     * 根据element获取value
     *
     * @param element
     * @return
     */
    public ReturnData getValueByElement(String element) {
        String value = Db.queryStr("select value from sys_config where element=?", element);
        ReturnData rd = new ReturnData(true);
        rd.setData(value);
        return rd;
    }

    /**
     * 根据cardId获取该用户及该订单的信息
     *
     * @param cardId
     * @return
     */
    public Record getOrderCardMemberByCardId(String cardId) {
        Record record = null;
        record = Db.findFirst("select orderId,memberId,cardNumber from card where id=?", cardId);
        return record;
    }

    /**
     * 根据支付结果存储
     *
     * @param
     * @return
     */

    public boolean toSaveSuccessPayResult(final String cardId, String msg, String code, String money, String realName, String alipayAccount) {
        final String cardId1 = cardId;
        final String msg1 = msg;
        final String code1 = code;
        final String money1 = money;
        final String realName1 = realName;
        final String alipayAccount1 = alipayAccount;
        return Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                try {
                    Db.update("update card set state = 5 , payState = 1, msg =? where id=?", "已打款", cardId1);
                    Db.update("update `order` set state =2 where id in (select orderId from card where id=?)", cardId1);

                    Record member = Db.findFirst("select * from yx_member where id =(select memberId from card where id =?)", cardId1);
                    Record accountLog = new Record().set("id", UuidUtil.get32UUID()).set("createTime", DateUtil.getTime())
                            .set("memberId", member.getStr("id")).set("realName", realName1)
                            .set("money", money1).set("msg", msg1).set("code", "000000")
                            .set("applyAccount", alipayAccount1);
                    String orderId = Db.queryStr("select orderId from card where id =? ", cardId1);

                    Record applyLog = new Record().set("id", UuidUtil.get32UUID()).set("realName", member.getStr("realName"))
                            .set("applyAccount", member.getStr("alipayAccount")).set("money", money1)
                            .set("cardId", cardId1).set("orderId", orderId).set("memberId", member.getStr("id"))
                            .set("createTime", DateUtil.getTime()).set("returnCode", "000000").set("returnMsg", msg1)
                            .set("returnJson", msg1).remove("msg");
                    Db.save("apply_logs", "id", applyLog);

                    Db.save("member_account_logs", "id", accountLog);
                } catch (Exception e) {
                    return false;
                }

                return true;
            }
        });

    }

    /**
     * 保存支付失败信息
     *
     * @param cardId
     * @param msg
     * @param code
     * @return
     */
    public boolean toSaveFailedPayResult(String cardId, String msg, String code, String realName, String alipayAccount) {
        final String cardId1 = cardId;
        final String msg1 = msg;
        final String code1 = code;
        final String realName1 = realName;
        final String alipayAccount1 = alipayAccount;
        return Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                try {
                    Db.update("update card set  payState = 2, msg =? where id=?", "打款失败", cardId1);
                    Record member = Db.findFirst("select * from yx_member where id =(select memberId from card where id =?)", cardId1);
                    Record accountLog = new Record().set("id", UuidUtil.get32UUID()).set("createTime", new Date())
                            .set("memberId", member.getStr("id")).set("realName", realName1)
                            .set("money", "0").set("msg", msg1).set("code", code1)
                            .set("applyAccount", alipayAccount1).set("orderId",cardId1);
                    Db.save("member_account_logs", "id", accountLog);
                } catch (Exception e) {
                    return false;
                }

                return true;
            }
        });

    }

    /**
     * 通过cardId付款
     *
     * @param cardId
     * @return
     */
    public ReturnData toPaybyCardId(String cardId, String amount, String realName, String alipayAccount) {

        Syslog.info("通过卡id向支付宝付款：" + cardId);

        ReturnData rd = new ReturnData();
        Map<String, String> map = new HashMap<>();

        try {
            Record card = Db.findFirst("select * from card where id=?", cardId);


            Record member = Db.findFirst("select * from yx_member where id=?", card.getStr("memberId"));

            Syslog.info("支付宝支付会员信息："+member.toJson());

            String saveRealName = realName == null || "".equals(realName) ? member.getStr("realName") : realName;
            String saveAlipayAccount = alipayAccount == null || "".equals(alipayAccount) ? member.getStr("alipayAccount") : alipayAccount;

            /*支付宝转账*/
            //if ( "2".equals(member.getStr("type"))) {//支付宝会员具有支付宝userId
            if (member.get("alipayId") !=null && "null".equals(member.get("alipayId"))==false
                    && "undefined".equals(member.get("alipayId"))==false &&
            "".equals(member.get("alipayId"))==false ) {//支付宝会员具有支付宝userId


                Syslog.info("通过userId向个人转账");

                map.put("payee_type", "ALIPAY_USERID");

                map.put("payee_account", member.getStr("alipayId"));
            } else {
                Syslog.info("通过真实姓名，支付宝保定账户向个人转账");
                map.put("payee_type", "ALIPAY_LOGONID");
                map.put("payee_account", saveAlipayAccount);
                //参数
                map.put("payee_real_name", saveRealName);
            }


            map.put("amount", amount);

            map.put("remark", card.getStr("cardNumber") + "_" + amount);



            map.put("cardId",card.getStr("cardNumber")==null||"".equals(card.getStr("cardNumber")) ||
                    "null".equals(card.getStr("cardNumber"))
                    ?card.getStr("cardPassword"):card.getStr("cardNumber"));

            Syslog.info("支付参数:" + map);

            AlipayFundTransToaccountTransferResponse response = null;//返回结果
            try {
                response = AlipayUtil.pay(map);

                Syslog.info(response.getBody());

            } catch (Exception e) {
                Syslog.error(e);
            }

            if (response != null) {
                if (response.isSuccess()) {
                    /**保存成功信息*/
                    toSaveSuccessPayResult(cardId, response.getMsg(), response.getCode(), amount, saveRealName, saveAlipayAccount);
                    /**添加返利信息*/
                    addRebateLog(member.getStr("id"),member.getStr("parentId"),card);
                    rd.setMsg(response.getMsg());
                    rd.setCode(response.getCode());
                    rd.setResult(true);
                } else {
                    toSaveFailedPayResult(cardId, response.getSubMsg(), response.getSubCode(), saveRealName, saveAlipayAccount);
                    String body=response.getBody();
                    rd.setMsg(response.getSubMsg());
                    rd.setCode(response.getSubCode());

                    toSaveFailedPayResult(cardId, response.getSubMsg(), response.getSubCode(),
                            saveRealName, saveAlipayAccount);
                    rd.setResult(false);
                    rd.setMsg("支付失败");

                }
                Syslog.info("支付结果:" + response.getMsg());
            } else {

                toSaveFailedPayResult(cardId, "支付失败", "111111", saveRealName, saveAlipayAccount);
                rd.setResult(false);
                rd.setMsg("支付失败");
            }
        } catch (Exception e) {

            Syslog.error(e);
            rd.setResult(false);
            rd.setMsg("支付异常");
        }
        return rd;

    }

    /**
     * 添加返利记录
     */
    public void addRebateLog(String id,String parentId,Record card){
        Record member = Db.findFirst("select * from yx_member where id='" + parentId + "'");

        if (member!=null){//有上级会员

            String rebatesThan= Db.queryStr("select rebatesThan from yx_member_rebates" +
                    " where faceValueId='" + card.getStr("feedbackId") + "' and memberId='"+parentId+"'");
            if (!member.getStr("agent").equals("0")||StringUtils.isBlank(rebatesThan)||"0".equals(rebatesThan)){
                return;
            }else {
                rebatesThan = new BigDecimal(rebatesThan).subtract(new BigDecimal(card.getStr("discount"))).toString();
                String amount = (new BigDecimal(card.getStr("feedbackValue")).multiply(new BigDecimal(rebatesThan))).setScale(1, BigDecimal.ROUND_UP).toString();
                Db.update("insert into rebatelog(memberId,parentId,rebateMoney) values('"+id+"','"+parentId+"','"+amount+"')");
                member.set("rebateMoney",new BigDecimal(member.getStr("rebateMoney")).add(new BigDecimal(amount)));
                Db.update("yx_member","id",member);
            }

        }


    }

    /**
     * 向代理商返利
     */
    public void rebateToAgent(String parentId,Record card,String saveRealName){
        Record member = Db.findFirst("select * from yx_member where id='" + parentId + "'");
        String rebatesThan= Db.queryStr("select rebatesThan from yx_member_rebates" +
                " where faceValueId='" + card.getStr("feedbackId") + "' and memberId='"+parentId+"'");
        if (!member.getStr("agent").equals("0")||StringUtils.isBlank(rebatesThan)||"0".equals(rebatesThan)){
            return;
        }else{
            rebatesThan=new BigDecimal(rebatesThan).subtract(new BigDecimal(card.getStr("time"))).toString();
            String amount=(new BigDecimal(card.getStr("feedbackValue")).multiply(new BigDecimal(rebatesThan))).setScale(1,BigDecimal.ROUND_UP).toString();
            Map<String, String> map=new HashMap();
            /*支付宝转账*/
            if ("3".equals(member.getStr("type")) || "5".equals(member.getStr("type"))) {//支付宝会员具有支付宝userId

                Syslog.info("通过userId向个人转账");

                map.put("payee_type", "ALIPAY_USERID");
                map.put("payee_account", member.getStr("alipayId"));
            } else {
                Syslog.info("通过真实姓名，支付宝保定账户向个人转账");
                map.put("payee_type", "ALIPAY_LOGONID");
                map.put("payee_account", member.getStr("alipayAccount"));
                //参数
                map.put("payee_real_name", member.getStr("realName"));
            }
            map.put("amount", amount);

            map.put("remark", "用户:"+saveRealName+"产生的返利");



            map.put("cardId",card.getStr("cardNumber")==null||"".equals(card.getStr("cardNumber")) ||
                    "null".equals(card.getStr("cardNumber"))
                    ?card.getStr("cardPassword"):card.getStr("cardNumber"));
            Syslog.info("支付参数:" + map);
            AlipayFundTransToaccountTransferResponse response = null;//返回结果
            try {
                response = AlipayUtil.pay(map);

                Syslog.info(response.getBody());

            } catch (Exception e) {
                Syslog.error(e);
            }
            if (response != null) {
                toSaveSuccessPayResult(card.getStr("id"), response.getMsg(), response.getCode(), amount, member.getStr("realName"), member.getStr("alipayAccount"));
                Syslog.info("支付结果:" + response.getMsg());
            } else {
                Syslog.info("未给代理商返利");
            }
        }
    }

    /**
     * 售卡记录
     */
    public PageUtil cardRecords(String id, String page, String limit) {
        String sql = "SELECT * FROM  card c LEFT JOIN yx_member yx   ON yx.id=c.memberId where c.memberId='" + id + "' order by c.upTime desc ";
        String countSql = "select count(id) from card where memberId ='" + id + "'";

        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    /**
     * 账号记录
     */
    public PageUtil acoUnt(String id, String page, String limit) {
        String sql = "SELECT * from yx_member ";
        String countSql = "select count(id) from yx_member where id ='" + id + "'";
        PageUtil PageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return PageUtil;
    }

    /**
     * 资金记录
     */
    public PageUtil moNey(String id, String page, String limit) {
        String sql = "SELECT *  from member_account_logs  WHERE memberId='" + id + "'";
        String countSql = "SELECT count(*) from member_account_logs  WHERE memberId='" + id + "'";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }


    /**
     * 取消或设定关联
     *
     * @param skId
     * @param isConn
     * @param id
     * @return
     */
    public ReturnData cancelSKConn(String skId, boolean isConn, String id) {
        String sql = "";
        ReturnData rd = new ReturnData();
        int row = 0;
        if (isConn) {
            //查询商品类型
            String commodityType = Db.queryStr("select type from commodity where id=(select commodityId from commodity_facevalue where id=?)", id);
            //将所有同一商品类型与选中面值的关联商品id相同的skCommodity=null
            String toRemove = "update commodity_facevalue set skCommodityId =null where skCommodityId=? and commodityId in(select id from commodity where type=?)";

            Db.update(toRemove, skId, commodityType);     //将原本关联的取消
            sql = "update commodity_facevalue set skCommodityId=? where id=?";
            row = Db.update(sql, skId, id);


        } else {
            sql = "update commodity_facevalue set skCommodityId=null where id =?";
            row = Db.update(sql, id);
        }
        if (row == 1) {
            rd.setResult(true);
            rd.setMsg("操作成功");
            rd.setCode("000000");
        } else {
            rd.setResult(false);
            rd.setMsg("操作失败");
            rd.setCode("111111");
        }
        return rd;
    }

    /**
     * 根据cardId获取订单信息
     */
    public Record getCardOrderByCardId(String cardId) {

        String sql = "select c.id as cardId, o.id as orderId,c.discount, c.cardNumber,c.cardPassword,c.state as cardState,c.feedbackValue ,c.msg as cardMsg, c.commodityId,c.classId,c.feedbackId  from card c left join `order` o on c.orderId=o.id where c.id=?";
        Record temp = Db.findFirst(sql, cardId);
        String cardSendId = Db.queryStr("select id from card_send_logs where cardId =?", cardId);
        /**获取支付宝信息*/
        String querySql = "select c.id as cardId , ym.realName, ym.alipayAccount ,ym.alipayId,(c.feedbackValue * c.discount) as money " +
                " from `order` o left join card c on c.orderId = o.id " +
                "left join yx_member ym on o.memberId = ym.id where c.id=? ";
        Record record = Db.findFirst(querySql, cardId);

        switch (temp.getStr("cardState")) {
            case "0":
                temp.set("cardStr", "处理中");
                break;
            case "1":
                temp.set("cardStr", "处理中");
                break;
            case "2":
                temp.set("cardStr", "处理中");
                break;
            case "3":
                temp.set("cardStr", "交易失败");
                break;
            case "4":
                temp.set("cardStr", "交易成功");
                break;
            case "5":
                temp.set("cardStr", "已打款");
                break;
            case "6":
                temp.set("cardStr", "交易失败");
                break;
        }
        if (cardSendId == null) {
            temp.set("sendWebSite", "未推送");

        } else {
            String sendWebSite = cardSendId.substring(0, 2);
            switch (sendWebSite) {
                case "XK":
                    temp.set("sendWebSite", "闲卡网");
                    break;
                case "SK":
                    temp.set("sendWebSite", "收卡网");
                    break;
                case "YJ":
                    temp.set("sendWebSite", "易缴费");
                    break;

            }
        }
        temp.set("alipay", record);
        return temp;
    }

    /**
     * 保存order card
     *
     * @param dataMap
     * @return
     */

    public ReturnData saveCardOrder(Map<String, String[]> dataMap) {

        ReturnData rd = new ReturnData();
        try {

            String cardId = dataMap.get("cardId")[0];
            String cardNumber = dataMap.get("cardNumber")[0];
            String cardPassword = dataMap.get("cardPassword")[0];
            String cardState = dataMap.get("cardState")[0];
            String discount = dataMap.get("discount")[0];

            //校验下面值
            String cardSql="SELECT *from card where id='"+cardId+"'";

            Record card=Db.findFirst(cardSql);


            if (Double.parseDouble(discount)>card.getDouble("discount")){


                rd.setResult(false);

                rd.setMsg("面值过大，请核对");

                return rd;
            }




            String newCardState = dataMap.get("newCardState")[0];
            String[] realName = dataMap.get("realName");
            String[] alipayAccount = dataMap.get("alipayAccount");
            String amount = dataMap.get("amount")[0];
            String cardMsg = dataMap.get("cardMsg")[0];


            if (newCardState != "-1") {   //用户进行了订单状态的变更
                switch (newCardState) {
                    case "1":     //处理中
                        cardState = "0";        //重新进行推送
                        cardMsg = "重新进行推送";
                        break;
                    case "2":     //交易成功,将进行付款
                        /**
                         * 如果已有支付成功记录,则不再支付
                         */
                        int payNum = Db.queryInt("select count(*) from apply_logs where cardId =? and (returnCode='0' or returnCode='000000' or returnCode='10000' )", cardId);
                        boolean shouldPay = payNum == 0 ? true : false;//是否进行支付
                        ReturnData payResult;


                        if (realName != null && alipayAccount != null) {


                            if (shouldPay) {
                                cardId=cardId==null||"".equals(cardId)?cardPassword:cardId;

                                payResult = toPaybyCardId(cardId, amount, realName[0], alipayAccount[0]);
                            } else {
                                payResult = new ReturnData(true);
                            }
                        } else {
                            if (shouldPay) {
                                cardId=cardId==null||"".equals(cardId)?cardPassword:cardId;
                                payResult = toPaybyCardId(cardId, amount, null, null);
                            } else {
                                payResult = new ReturnData(true);
                            }
                        }

                        if (payResult.isResult()) { //支付成功
                            cardState = "5";
                            cardMsg = "交易成功,已打款";
                        } else {        //支付失败
                            cardState = "6";
                            cardMsg = "交易成功,付款失败";
                            rd.setResult(false);
                            rd.setCode("222222");
                            rd.setMsg("付款失败");
                            return rd;

                        }

                        break;
                    case "3":     //交易失败,如果cardState不等于3 ||6,将置为6
//                        if (!"3".equals(cardState) && !"6".equals(cardState)) {
//                            cardState = "3";
//                        }

                        cardState = "3";
                        break;
                }

            }


            int row1 = Db.update("update card set cardNumber =?,payTime=now(),cardPassword=?,state=?,discount=?,msg=? where id=?",

                    cardNumber, cardPassword, cardState, discount, cardMsg, cardId);

            if (row1 == 1) {
                rd.setResult(true);
            } else {
                rd.setResult(false);
                rd.setMsg("内部异常");
            }
        } catch (Exception e) {
            rd.setResult(false);
            rd.setMsg("数据填写错误1");
            rd.setCode("111111");
        }
        return rd;
    }

    /**
     * @param
     * @param
     * @return
     */
    public PageUtil showXKList(String limit, String page,String key) {


        String countSql = "select count(id) from xy_commodity where 1=1 ";
        String sql = "select * from xy_commodity   where 1=1 ";

        if ("".equals(key)==false && key!=null){
            countSql+=" and commodityName like '%"+key+"%'";
            sql+=" and commodityName like '%"+key+"%'";
        }

        sql+=" order by commodityTypeId,commodityId";
        PageUtil pageUtil = new PageUtil(Integer.valueOf(page), Integer.valueOf(limit), sql, countSql);
        return pageUtil;
    }

    /**
     * 查询建议
     *
     * @param
     * @param
     * @return
     */
    public PageUtil rmeoVEd(Map<String, String[]> map) {
        String limit[] = map.get("limit");
        String page[] = map.get("page");
        String limitStr = "";
        String pageStr = "";
        String id[] = map.get("id");
        String type[]=map.get("type");
        if (type==null)type=new String[]{"0"};
        if (limit == null && page == null) {
            limitStr = "10";
            pageStr = "1";
        } else {
            limitStr = limit[0];
            pageStr = page[0];
        }
        String sql = "select * from feedback where 1=1";
        String countsql = "select count(*) from feedback where 1=1";
        if (StringUtils.isNotBlank(type[0])){
            sql+=" and type="+type[0];
            countsql+=" and type="+type[0];
        }
        sql+=" Order By createTime Desc";
        PageUtil pageUtil = new PageUtil(Integer.valueOf(pageStr), Integer.valueOf(limitStr), sql, countsql);
        return pageUtil;
    }

    /**
     * 删除建议
     *
     * @param
     * @return
     */
    public ReturnData remove(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String sql = "DELETE from feedback where id='" + id + "'";
        int del = delete(sql);
        if (del == 1) {
            returnData.setCode("000000");
            returnData.setResult(true);
        } else {
            returnData.setCode("111111");
            returnData.setResult(false);
        }
        return returnData;
    }

    /**
     * 热门商品select 选项
     *
     * @return
     */
    public List<Record> getCommodityListForHotList() {
        /**
         * 0 PC商品
         * 1 移动端商品
         * 2 支付宝商品
         * 3 小程序1商品
         * 4 小程序2商品
         * 5 小程序3商品
         * 6 小程序4商品
         * 7 app端商品
         */
        List<Record> list = Db.find("select * from commodity where state!=3");
        for (Record r : list) {
            switch (r.getStr("type")) {
                case "0":
                    r.set("typeName", "(PC商品)");
                    break;
                case "1":
                    r.set("typeName", "(移动端商品)");
                    break;
                case "2":
                    r.set("typeName", "(支付宝)");
                    break;
                case "3":
                    r.set("typeName", "(小程序1)");
                    break;
                case "4":
                    r.set("typeName", "(小程序2)");
                    break;
                case "5":
                    r.set("typeName", "(小程序3)");
                    break;
                case "6":
                    r.set("typeName", "(小程序4)");
                    break;
                case "7":
                    r.set("typeName", "(app)");
                    break;
            }
        }
        return list;
    }

    /**
     * 设置是否有卡号
     *
     * @param hasCardNumber
     * @param id
     * @param tableName     //表名
     * @return
     */
    public ReturnData setHasCardNumber(String hasCardNumber, String id, String tableName) {
        ReturnData rd = new ReturnData();
        int row = Db.update("update " + tableName + " set hasCardNumber = ? where id =? ", hasCardNumber, id);
        if (row == 1) {
            rd.setResult(true);
        } else {
            rd.setResult(false);
        }
        return rd;
    }

    /**
     * 根据订单Id重新推送
     *
     * @param cardId
     * @return
     */
    public Record reSubmitCard(String cardId) {


        //根据面值查出卡种信息

        Record card = Db.findFirst("select * from card where id = ?", cardId);
        Record order = Db.findFirst("select * from `order` where id =?", card.getStr("orderId"));
        String cardState = card.getStr("state");
        Record commodityApiType = Db.findFirst("select * from commodity_api_number where faceValueId =? order by number asc", card.getStr("feedbackId"));


        if (commodityApiType!=null){

            String apiType = commodityApiType.getStr("apiType");
            switch (apiType) {
                case "0":
                    card.set("sendWebSite", "易缴费");
                    break;
                case "1":
                    card.set("sendWebSite", "闲卡网");
                    break;
                case "2":
                    card.set("sendWebSite", "收卡啦");
                    break;
                case "3":
                    card.set("sendWebSite", "速销卡");
                    break;
                case "4":
                    card.set("sendWebSite", "蜜蜂平台");
                    break;
            }
        }else {

            card.set("sendWebSite", "未配置推卡平台");

        }




        switch (cardState) {
            case "0":
                card.set("cardStr", "处理中");
                break;
            case "1":
                card.set("cardStr", "处理中");
                break;
            case "2":
                card.set("cardStr", "处理中");
                break;
            case "3":
                card.set("cardStr", "交易失败");
                break;
            case "4":
                card.set("cardStr", "交易成功");
                break;
            case "5":
                card.set("cardStr", "已打款");
                break;
            case "6":
                card.set("cardStr", "交易失败");
                break;
        }
        List<Record> list = Db.find("select * from commodity_facevalue where commodityId =?", card.getStr("commodityId"));//@TODO
        Record record = new Record().set("card", card).set("order", order).set("facevalueList", list);
        return record;
    }

    /**
     * 重新提交订单
     *
     * @param dataMap
     * @return
     */
    public ReturnData submitCard(Map<String, String[]> dataMap) {
        ReturnData rd = new ReturnData();
        String cardId = dataMap.get("cardId")[0];

        cache.del("send"+cardId);


        cache.del(cardId);

        String cardNumber = dataMap.get("cardNumber")[0];
        String cardPassword = dataMap.get("cardPassword")[0];
        String faceValueId = dataMap.get("facevalue")[0];
        String discount = dataMap.get("discount")[0];

        String facevalueSql="select *from commodity_facevalue where id='"+faceValueId+"' ";

        Record facevalueRecord=Db.findFirst(facevalueSql);

        if (Double.parseDouble(discount)> facevalueRecord.getDouble("discount")){

            rd.setResult(true);
            rd.setCode("000000");
            rd.setMsg("折扣率不符，请检查");
            return rd;


        }



        String faceValue = Db.queryStr("select facevalue from commodity_facevalue where id =?", faceValueId);
        /**删除之前的推送记录*/
        Syslog.info("重新推送cardId=" + cardId);
        Db.update("delete from card_send_logs where cardId =(select id from card where id =? )", cardId);
        //Db.deleteById("card_send_logs","id","");
        Db.update("update card set cardNumber=?,cardPassword =?,feedbackId =?,discount=?,feedbackValue =? ,state = 0,msg='重新提交',upTime=? where id=?"
                , cardNumber, cardPassword, faceValueId, discount, faceValue, DateUtil.getTime(), cardId
        );


        new SendCardTask().run();
        rd.setResult(true);
        rd.setCode("000000");
        rd.setMsg("已重新推送");
        return rd;
    }
    /**
     * 卡支付记录
     */
    PageUtil aliLogService(String cardId){

        String sql="SELECT *from member_account_logs where orderId='"+cardId+"' order by createTime desc ";

        PageUtil pageUtil=new PageUtil(1,999,sql);

        return pageUtil;

    }

    /**
     * 配置返利
     */
    public PageUtil agent(String id, String page, String limit,String commodityName,String faceValue) {
        String sql = "select a.id, 0 as  rebatesThan,c.name as  commodityName,b.faceValue, b.id as faceValueId from" +
                "  commodity_facevalue b LEFT JOIN yx_member_rebates a  on a.faceValueId=b.id LEFT JOIN commodity c " +
                "on b.commodityId=c.id where c.state!='3' and  a.memberId='"+id+"'  ";
        if (StringUtils.isNotBlank(commodityName))sql+=" and c.name like '%"+commodityName+"%'";
        if (StringUtils.isNotBlank(faceValue))sql+=" and b.faceValue="+faceValue;
        //查询出会员的返利配置
        String memberReSql="SELECT *from yx_member_rebates where memberId='"+id+"'";

        List<Record> list=Db.find(memberReSql);

        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql);

        for (int i=0;i<pageUtil.getList().size();i++){

            Record record= (Record) pageUtil.getList().get(i);

            String faceValueId=record.getStr("faceValueId");//面值ID

            String rebatesThan=record.getStr("rebatesThan");//返利值

            for (int j=0;j<list.size();j++){

                Record mem=list.get(j);

                String faceValueIdMem=mem.getStr("faceValueId");

                String rebatesThanMem=mem.getStr("rebatesThan");

                if (faceValueId.equals(faceValueIdMem)){//面值相同

                    rebatesThan=rebatesThanMem;//将当前会员的赋值给他
                }

            }
            record.set("rebatesThan",rebatesThan);


            pageUtil.getList().set(i,record);

        }

        return pageUtil;
    }

    /**
     * 代理商下级人员
     */
    public PageUtil subordinate(String id, String page, String limit,String name) {
        String sql = "select id,name,realName from yx_member where parentId='" + id + "'";
        if (StringUtils.isNotBlank(name))sql+=" and name like '%"+name+"%'";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql);
        return pageUtil;
    }

    /**
     * 修改返利配置
     */
    public Record editAgent(String id) {
        String sql="SELECT *from yx_member_rebates where id='"+id+"'";
        Record first = Db.findFirst(sql);
        return first;
    }

    /**
     * 保存返利配置
     */
    public ReturnData saveAgent(Map<String, String[]> paraMap) {
        ReturnData returnData=new ReturnData();
        Record record = MapToRecord.getRecord(paraMap);

        boolean update=false;

        if (record.get("id")==null ||  "".equals(record.get("id")+"") || "undefined".equals(record.get("id")+"")){//没有设置返利比例

            record.remove("id");
            update=Db.save("yx_member_rebates",record);

        }else {
            update = Db.update("yx_member_rebates", "id", record);
        }


        if (update){
            returnData.setResult(true);
            returnData.setMsg("配置成功");
        }else{
            returnData.setResult(false);
            returnData.setMsg("未配置成功");
        }
        return returnData;
    }

    /**
     * 添加下级
     */
    public ReturnData addSubordinate(String id, String userId) {
        ReturnData returnData=new ReturnData();
        String parentId = Db.queryStr("select parentId from yx_member where id='" + userId + "'");
        if (StringUtils.isBlank(userId)){
            returnData.setResult(false);
            returnData.setMsg("会员id不能为空！");
        }else if (id.equals(parentId)){
            returnData.setResult(false);
            returnData.setMsg("该代理商已有此下级会员，请勿重复添加！");
        }else if (StringUtils.isNotBlank(parentId)){
            returnData.setResult(false);
            returnData.setMsg("该会员已属于其他代理商！");
        }else if(id.equals(userId)){
            returnData.setResult(false);
            returnData.setMsg("代理商还能添加自己为下级？？？");
        }else{
            boolean update = Db.update("yx_member", "id", new Record().set("id", userId).set("parentId", id));
            if (update){
                returnData.setResult(true);
                returnData.setMsg("添加成功");
            }else{
                returnData.setResult(false);
                returnData.setMsg("没有该会员！");
            }
        }
        return returnData;
    }

    /**
     * 解除下级
     */
    public ReturnData delSubordinate(String id, String userId) {
        ReturnData returnData=new ReturnData();
        Record first = Db.findFirst("select * from yx_member where id='" + userId + "' and parentId='" + id + "'");
        if (first==null){
            returnData.setResult(false);
            returnData.setMsg("数据错误请刷新后重试!");
            return returnData;
        }
        boolean update = Db.update("yx_member", "id", new Record().set("id", userId).set("parentId", null));
        if (update){
            returnData.setResult(true);
            returnData.setMsg("解除成功");
        }else{
            returnData.setResult(false);
            returnData.setMsg("解除失败");
        }
        return returnData;
    }
    //一键复制卡种以及面值

    public ReturnData oneButonCopySaveService(Map<String,String[]> map){

        String commodityId=map.get("id")[0];//当前卡种

        String commoditySql="SELECT *from commodity where id='"+commodityId+"'";

        Record commodity=Db.findFirst(commoditySql);

        //查出来对应的卡类
        String classId=commodity.getStr("classId");

        String calssSql="select *from  commodity_class  where id='"+classId+"'";

        Record classRecord=Db.findFirst(calssSql);


        String classCopySql="";



        if ("".equals(classRecord.getStr("synchronization")) || classRecord.get("synchronization")==null){


            classCopySql="select *from  commodity_class where name='"+classRecord.getStr("name")+"' ";

        }else {

            classCopySql="select *from  commodity_class where synchronization='"+classRecord.getStr("synchronization")+"' ";
        }


        String baseSql=classCopySql;

        //查出来
        if (map.get("0")!=null){


            classCopySql=baseSql+" and cType="+0;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();

            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId).set("id",UuidUtil.get32UUID());
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());



        }
        if (map.get("1")!=null){
            classCopySql=baseSql+" and cType="+1;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();
            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId);
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());
        }
        if (map.get("2")!=null){
            classCopySql=baseSql+" and cType="+2;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();
            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId);
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());
        }
        if (map.get("3")!=null){
            classCopySql=baseSql+" and cType="+3;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();
            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId);
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());
        }
        if (map.get("4")!=null){
            classCopySql=baseSql+" and cType="+4;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();
            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId);
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());
        }
        if (map.get("5")!=null){
            classCopySql=baseSql+" and cType="+5;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();
            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId);
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());
        }
        if (map.get("6")!=null){
            classCopySql=baseSql+" and cType="+6;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();
            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId);
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());
        }
        if (map.get("7")!=null){
            classCopySql=baseSql+" and cType="+7;

            Record classCopyRecord=Db.findFirst(classCopySql);

            //新的卡种
            String nowId=UtilUUID.getUUID();
            Record nowRecord=new Record().setColumns(commodity).set("id",nowId)
                    .set("classId",classCopyRecord.getStr("id"))
                    .set("className",classCopyRecord.getStr("name"));
            Db.save("commodity","id",nowRecord);//复制卡种


            //查出来所有的面值
            String facevalueSql="SELECT *from commodity_facevalue WHERE commodityId='"+commodityId+"'";

            List<Record> facevalueList=Db.find(facevalueSql);

            for (int i =0;i<facevalueList.size();i++){

                facevalueList.get(i).set("commodityId",nowId);
            }

            Db.batchUpdate("commodity_facevalue",facevalueList,facevalueList.size());
        }


        return new ReturnData(true);

    }


}

